<template>
  <view class="container">
  
    <!-- 用户信息和时间 -->
    <view class="user-info-card">
      <view class="date-time">
        <text class="date">{{ currentDate }}</text>
        <text class="time">{{ currentTime }}</text>
      </view>
      <view class="user-detail">
        <cloud-image width="100rpx" height="100rpx" v-if="hasLogin&&userInfo.avatar_file&&userInfo.avatar_file.url" :src="userInfo.avatar_file.url"></cloud-image>
        
        <view v-else class="defaultAvatarUrl">
        	<image src="/static/logo.png" mode="widthFix" style="width: 40px;"></image>
        </view>
        <view class="user-text">
          <text class="name">{{ userInfo.nickname || userInfo.username || '加载中...' }}</text>
          <text class="department">{{ '普通用户' }}</text>
        </view>
      </view>
    </view>
    
    <!-- 打卡主区域 -->
    <view class="punch-main">
      <view class="punch-btn-container" @click="handlePunch">
        <view class="punch-btn" :class="{ disabled: punchLoading }">
		  <uni-icons type="location"  color="#fff" size="50"></uni-icons>
          <text class="btn-text">{{ punchLoading ? '打卡中...' : '打卡' }}</text>
        </view>
      </view>
      
      <view class="location-info">
        <uni-icons type="location"  color="#666" size="20"></uni-icons>
        <text class="location-text">{{ locationInfo.address || '定位中...' }}</text>
      </view>
    </view>
    
    <!-- 今日统计 -->
    <view class="stats-card">
      <view class="card-header">
        <text class="title">今日统计</text>
        <text class="date">{{ currentDate }}</text>
      </view>
      
      <view class="stats-content">
        <view class="stat-item">
          <text class="value">{{ todayStats.work_duration ? formatDuration(todayStats.work_duration) : '--' }}</text>
          <text class="label">工作时长</text>
        </view>
        <view class="stat-item">
          <text class="value">{{ todayStats.punch_count || 0 }}</text>
          <text class="label">打卡次数</text>
        </view>
        <view class="stat-item">
          <text class="value" :class="{ warn: todayStats.status === 'abnormal' }">
            {{ formatStatus(todayStats.status) }}
          </text>
          <text class="label">考勤状态</text>
        </view>
      </view>
    </view>
    
    <!-- 打卡记录 -->
    <view class="records-card">
      <view class="card-header">
        <text class="title">打卡记录</text>
        <text class="toAll" size="mini" plain @click="viewAllRecords">查看全部</text>
      </view>
      
      <view v-if="loading" class="loading">
        <u-loading-icon ></u-loading-icon>
        <text>加载中...</text>
      </view>
      
      <view v-else-if="todayRecords.length === 0" class="no-data">
        <u-empty text="今日暂无打卡记录" mode="list"></u-empty>
      </view>
      
      <view v-else class="records-list">
        <view v-for="(record, index) in todayRecords" :key="index" class="record-item">
          <view class="record-time">
            <text class="time">{{ formatTime(record.punch_time) }}</text>
            <text class="type">{{ record.type === 'check_in' ? '上班打卡' : '下班打卡' }}</text>
          </view>
          <view class="record-status" :class="record.status">
            {{ formatRecordStatus(record.status) }}
          </view>
        </view>
      </view>
    </view>
    
    <!-- 打卡弹窗 -->
    <u-modal :show="showPunchModal" :show-cancel-button="true" 
             :confirm-text="punchLoading ? '打卡中...' : '确认打卡'" 
             cancel-text="取消" 
             :async-close="true" 
             @confirm="confirmPunch" 
             @cancel="closePunchModal"
             title="考勤打卡"
             :show-confirm-button="!cameraLoading">
      <view class="punch-modal-content">
        <!-- 打卡信息 -->
        <view class="punch-info">
          <view class="info-item">
            <text>时间: {{ currentTime }}</text>
          </view>
          <view class="info-item">
            <text>位置: {{ locationInfo.address || '定位中...' }}</text>
          </view>
        </view>
      </view>
    </u-modal>
  </view>
</template>

<script>
const db = uniCloud.database();
const dbCmd = db.command;
import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'
export default {
  data() {
    return {
      pageTitle: '考勤打卡',
      currentDate: '',
      currentTime: '',
      locationInfo: {
        address: '',
        latitude: null,
        longitude: null
      },
      todayStats: {
        work_duration: 0,
        punch_count: 0,
        status: 'normal'
      },
      todayRecords: [],
      showPunchModal: false,
      showCamera: false,
      cameraLoading: false,
      photoLoading: false,
      photoPath: '',
      punchLoading: false,
      loading: true,
      timer: null,
      attendanceRule: null
    }
  },
  onLoad() {
    this.updateDateTime();
    this.getLocation();
    this.loadAttendanceRule();
    this.loadTodayData();
    // 每秒更新一次时间
    this.timer = setInterval(() => {
      this.updateDateTime();
    }, 1000);
  },
  onUnload() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  computed: {
  	userInfo() {
  		return store.userInfo
  	},
  	hasLogin(){
  		return store.hasLogin
  	},
  	appConfig() {
  		return getApp().globalData.config
  	}
  },
  methods: {
    // 更新日期时间
    updateDateTime() {
      const now = new Date();
      this.currentDate = now.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      });
      this.currentTime = now.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },
    
    // 获取位置信息
    getLocation() {
	// #ifndef H5
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          this.locationInfo.latitude = res.latitude;
          this.locationInfo.longitude = res.longitude;
          
          // 逆地理编码获取地址
          this.reverseGeocode(res.latitude, res.longitude);
        },
        fail: (err) => {
          console.error('获取位置失败:', err);
          this.locationInfo.address = '获取位置失败';
        }
      });
	  // #endif
    },
    
    // 逆地理编码
    reverseGeocode(latitude, longitude) {
      // 这里应该是调用地图API进行逆地理编码
      // 由于需要密钥，这里模拟一个地址
      setTimeout(() => {
        this.locationInfo.address = '北京市海淀区中关村大街1号';
      }, 1500);
    },
    // 加载考勤规则
    async loadAttendanceRule() {
      try {
          const ruleRes = await db.collection('mydb-attendance-rules').where({is_default:true}).get();
          if (ruleRes.result.data) {
            this.attendanceRule = ruleRes.result.data[0];
          }
      } catch (err) {
        console.error('加载考勤规则失败:', err);
      }
    },
    
    // 加载今日数据
    async loadTodayData() {
      try {
        this.loading = true;
        
        // 获取今日0点时间戳
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const todayStart = today.getTime();
        
        // 获取今日打卡记录
        const recordsRes = await db.collection('mydb-attendance-record')
          .where({
            user_id: dbCmd.eq(this.userInfo._id),
            punch_time: dbCmd.gte(todayStart)
          })
          .orderBy('punch_time', 'desc')
          .get();
        
        this.todayRecords = recordsRes.result.data;
        
        // 获取今日统计
        const statsRes = await db.collection('mydb-attendance-stats')
          .where({
            user_id: this.userInfo._id,
            date: dbCmd.eq(todayStart)
          })
          .get();
        
        if (statsRes.result.data.length > 0) {
          this.todayStats = statsRes.result.data[0];
        } else {
          // 如果没有统计记录，创建一条
          this.todayStats = {
            user_id: this.userInfo._id,
            date: todayStart,
            work_duration: 0,
            punch_count: 0,
            status: 'normal'
          };
        }
        
        this.loading = false;
      } catch (err) {
        console.error('加载今日数据失败:', err);
        this.loading = false;
        uni.showToast({
          title: '加载数据失败',
          icon: 'none'
        });
      }
    },
    
    // 处理打卡点击
    handlePunch() {
      if (this.punchLoading) return;
      
      this.showPunchModal = true;
    },
    // 确认打卡
    async confirmPunch() {
      this.punchLoading = true;
      try {
        const now = new Date();
        const punchTime = now.getTime();
        
        // 判断打卡类型
        const hour = now.getHours();
        let type = 'check_in';
        let status = 'normal';
        
        if (hour >= 12) {
          type = 'check_out';
        }
        console.log('this.attendanceRule',this.attendanceRule)
        // 根据考勤规则判断状态
        if (this.attendanceRule) {
          if (type === 'check_in') {
            const [startHour, startMinute] = this.attendanceRule.work_start_time.split(':');
            const workStart = new Date();
            workStart.setHours(parseInt(startHour), parseInt(startMinute), 0, 0);
            
            if (now > workStart) {
              const lateMinutes = Math.floor((now - workStart) / 60000);
              if (lateMinutes > this.attendanceRule.late_minutes) {
                status = 'late';
              }
            }
          } else if (type === 'check_out') {
            const [endHour, endMinute] = this.attendanceRule.work_end_time.split(':');
            const workEnd = new Date();
            workEnd.setHours(parseInt(endHour), parseInt(endMinute), 0, 0);
            
            if (now < workEnd) {
              const earlyMinutes = Math.floor((workEnd - now) / 60000);
              if (earlyMinutes > this.attendanceRule.early_minutes) {
                status = 'early';
              }
            }
          }
        }
        
      
        // 插入打卡记录
        const recordData = {
		  user_id: this.userInfo._id,
          punch_time: punchTime,
          type: type,
          status: status,
          location: {
            latitude: this.locationInfo.latitude,
            longitude: this.locationInfo.longitude,
            address: this.locationInfo.address
          },
          device_info: {
            model: uni.getSystemInfoSync().model,
            platform: uni.getSystemInfoSync().platform,
            ip: '' // 需要后端获取，前端无法直接获取IP
          }
        };
        
        await db.collection('mydb-attendance-record').add(recordData);
        
        // 更新今日统计
        await this.updateAttendanceStats(type, punchTime, status);
        
        // 关闭弹窗
        this.showPunchModal = false;
        this.photoPath = '';
        this.showCamera = false;
        this.punchLoading = false;
        
        // 重新加载数据
        this.loadTodayData();
        
        uni.showToast({
          title: '打卡成功',
          icon: 'success'
        });
        
      } catch (err) {
        console.error('打卡失败:', err);
        uni.showToast({
          title: '打卡失败',
          icon: 'none'
        });
        this.punchLoading = false;
      }
    },
    
    // 更新考勤统计
    async updateAttendanceStats(type, punchTime, status) {
      // 获取当日0点时间戳
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const dateTimestamp = today.getTime();
      
      try {
        // 查询是否已有当日统计
        const statsRes = await db.collection('mydb-attendance-stats')
          .where({
            user_id: dbCmd.eq(this.userInfo._id),
            date: dbCmd.eq(dateTimestamp)
          })
          .get();
        
        if (statsRes.result.data.length > 0) {
          // 更新现有统计
          const statsData = statsRes.result.data[0];
          const updateData = {};
          
          if (type === 'check_in') {
            updateData.check_in_time = punchTime;
          } else {
            updateData.check_out_time = punchTime;
          }
          
          // 如果上下班时间都有，计算工作时长
          if (updateData.check_in_time && updateData.check_out_time) {
            const workDuration = Math.floor((updateData.check_out_time - updateData.check_in_time) / 60000); // 分钟
            updateData.work_duration = workDuration;
          }
          
       
          
          updateData.punch_count = dbCmd.inc(1);
          
          await db.collection('mydb-attendance-stats').doc(statsData._id).update(updateData);
        } else {
          // 创建新的统计记录
          const statsData = {
            user_id: this.userInfo._id,
            date: dateTimestamp,
            work_duration: 0,
            punch_count: 1,
            status,
          };
          
          if (type === 'check_in') {
            statsData.check_in_time = punchTime;
          } else {
            statsData.check_out_time = punchTime;
          }
          
          await db.collection('mydb-attendance-stats').add(statsData);
        }
      } catch (err) {
        console.error('更新统计失败:', err);
      }
    },
    
    // 关闭打卡弹窗
    closePunchModal() {
      this.showPunchModal = false;
      this.photoPath = '';
      this.showCamera = false;
    },
    
    // 查看全部记录
    viewAllRecords() {
      uni.navigateTo({
        url: '/pages/attendance/records'
      });
    },
    
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },
    
    // 格式化时长
    formatDuration(minutes) {
      if (!minutes) return '0分钟';
      const hours = Math.floor(minutes / 60);
      const mins = minutes % 60;
      
      if (hours > 0) {
        return `${hours}小时${mins}分钟`;
      } else {
        return `${mins}分钟`;
      }
    },
    
    // 格式化状态
    formatStatus(status) {
      const statusMap = {
        'normal': '正常',
        'abnormal': '异常',
        'late': '迟到',
        'early': '早退',
        'absent': '缺勤'
      };
      return statusMap[status] || '未知';
    },
    
    // 格式化记录状态
    formatRecordStatus(status) {
      const statusMap = {
        'normal': '正常',
        'late': '迟到',
        'early': '早退',
        'abnormal': '异常'
      };
      return statusMap[status] || '未知';
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.user-info-card {
  background: linear-gradient(135deg, #2979ff, #2962ff);
  border-radius: 16rpx;
  padding: 30rpx;
  color: white;
  margin-bottom: 30rpx;
  box-shadow: 0 10rpx 20rpx rgba(41, 121, 255, 0.2);
  
  .date-time {
    display: flex;
    flex-direction: column;
    margin-bottom: 30rpx;
    
    .date {
      font-size: 36rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
    }
    
    .time {
      font-size: 32rpx;
      opacity: 0.9;
    }
  }
  
  .user-detail {
    display: flex;
    align-items: center;
    
    .user-text {
      margin-left: 20rpx;
      display: flex;
      flex-direction: column;
      
      .name {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 5rpx;
      }
      
      .department {
        font-size: 26rpx;
        opacity: 0.8;
      }
    }
  }
}

.punch-main {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 40rpx 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30rpx;
  box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.05);
  
  .punch-btn-container {
    margin-bottom: 30rpx;
    
    .punch-btn {
      width: 200rpx;
      height: 200rpx;
      border-radius: 50%;
      background: linear-gradient(135deg, #2979ff, #2962ff);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: white;
      box-shadow: 0 10rpx 30rpx rgba(41, 121, 255, 0.4);
      
      &.disabled {
        opacity: 0.7;
      }
      
      .btn-text {
        margin-top: 15rpx;
        font-size: 32rpx;
        font-weight: bold;
      }
    }
  }
  
  .location-info {
    display: flex;
    align-items: center;
    color: #666;
    font-size: 28rpx;
    
    .location-text {
      margin-left: 10rpx;
    }
  }
}

.stats-card,
.records-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.05);
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .title {
      font-size: 32rpx;
      font-weight: bold;
    }
    
    .date {
      font-size: 26rpx;
      color: #999;
    }
	.toAll{
      font-size: 26rpx;
      color: #999;
    }
  }
}

.stats-content {
  display: flex;
  justify-content: space-around;
  
  .stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .value {
      font-size: 36rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
      
      &.warn {
        color: #f44336;
      }
    }
    
    .label {
      font-size: 26rpx;
      color: #999;
    }
  }
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0;
  
  text {
    margin-top: 20rpx;
    color: #999;
  }
}

.records-list {
  .record-item {
    display: flex;
    justify-content: space-between;
    padding: 25rpx 0;
    border-bottom: 1rpx solid #f1f1f1;
    
    &:last-child {
      border-bottom: none;
    }
    
    .record-time {
      display: flex;
      flex-direction: column;
      
      .time {
        font-size: 32rpx;
        font-weight: 500;
        margin-bottom: 5rpx;
      }
      
      .type {
        font-size: 26rpx;
        color: #999;
      }
    }
    
    .record-status {
      font-size: 28rpx;
      padding: 8rpx;
      line-height: 24px;
      &.normal {
        background-color: #e8f5e9;
        color: #4caf50;
      }
      
      &.late, &.early, &.abnormal {
        background-color: #ffebee;
        color: #f44336;
      }
    }
  }
}

.punch-modal-content {
  .camera-container {
    width: 100%;
    height: 400rpx;
    background: #f1f1f1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-bottom: 30rpx;
    border-radius: 10rpx;
    overflow: hidden;
    
    .camera {
      width: 100%;
      height: 100%;
    }
    
    .camera-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      color: #999;
      
      text {
        margin-top: 20rpx;
      }
    }
    
    .camera-actions {
      margin-top: 20rpx;
    }
  }
  
  .photo-preview {
    margin-bottom: 30rpx;
    
    .photo {
      width: 100%;
      height: 400rpx;
      border-radius: 10rpx;
    }
    
    .photo-actions {
      margin-top: 20rpx;
      display: flex;
      justify-content: center;
    }
  }
  
  .punch-info {
    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 15rpx;
      font-size: 28rpx;
      
      text {
        margin-left: 10rpx;
      }
    }
  }
}
</style>